import 'package:flutter/cupertino.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

class StateLayout extends StatefulWidget {
  final StateType type;
  final String? emptyImg;
  final String? hintText;
  final String? errorImg; //加载错误，图片
  final Function? onRefresh;
  final Widget? loadingWidget;

  const StateLayout({
    Key? key,
    required this.type,
    this.emptyImg,
    this.hintText,
    this.errorImg,
    this.onRefresh,
    this.loadingWidget,
  }) : super(key: key);

  @override
  State<StateLayout> createState() => _StateLayoutState();
}

class _StateLayoutState extends State<StateLayout> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: widget.type == StateType.loading
          ? widget.loadingWidget ?? _loadingWidget()
          : _otherWidget(),
    );
  }

  Widget _loadingWidget() {
    return const Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CupertinoActivityIndicator(radius: 16.0),
      ],
    );
  }

  Widget _otherWidget() {
    switch (widget.type) {
      case StateType.network:
        return _buildNormalView(widget.errorImg, '无网络连接');
      case StateType.loading:
        return Container();
      case StateType.empty:
        return _buildNormalView(widget.emptyImg, widget.hintText ?? '暂无数据');
      case StateType.error:
        return _buildNormalView(widget.errorImg, '加载失败，请点击重试');
      case StateType.success:
        return Container();
    }
  }

  Widget _buildNormalView(String? img, String hintText) {
    return GestureDetector(
      onTap: () {
        if (widget.onRefresh != null) {
          widget.onRefresh!();
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const SizedBox(height: 30.0),
          img != null && img.isNotEmpty
              ? ImageWidget.loadAssetImage(
                  img,
                  width: 133.5 * 2,
                  height: 95 * 2,
                  package: "flutter_clx_base",
                )
              : const SizedBox(),
          Text(
            hintText,
            style: const TextStyle(
              color: Color(0xff86909C),
              fontSize: 14.0,
              fontWeight: FontWeight.normal,
            ),
          ),
          const SizedBox(height: 30.0),
        ],
      ),
    );
  }
}

enum StateType {
  /// 无网络
  network,

  /// 加载中
  loading,

  /// 空
  empty,

  ///异常
  error,

  ///成功
  success
}
